// 定义品类的数据结构
interface ICategory {
  id: number;
  name: string;
  unit: string;
  unitPrice: number;
}

// 定义出货条目的数据结构
interface IOutboundItem {
  key: number; // 用于 wx:for 的唯一 key
  categoryId: number | null;
  name: string;
  unit: string;
  unitPrice: number;
  quantity: string; // 使用字符串以处理小数点输入过程
  totalPrice: string;
}
// 1. 定义 Properties 类型
interface IComponentProperties {
  item: IOutboundItem;
  isCharityMode: boolean;
  allCategories: ICategory[];
  index: number;
}

// 2. 定义 Data 类型
interface IComponentData {
  categoryPickerRange: string[];
  pickerIndex: number;
}

// 3. 定义 Methods 类型 (所有方法的集合)
interface IComponentMethods {
  updatePickerRange(): void;
  onCategoryChange(e: WechatMiniprogram.PickerChange): void; // 使用更精确的事件类型
  handleTapDisabledInput(): void;
  onQuantityInput(e: WechatMiniprogram.Input): void; // 使用更精确的事件类型
  calculateAndEmit(item: IOutboundItem): void;
  onDelete(): void;
}

Component<IComponentData, IComponentProperties, IComponentMethods>({
  properties: {
    // 从页面接收的单个条目数据
    item: {
      type: Object as () => IOutboundItem,
      value: {},
    },
    isCharityMode: {
      type: Boolean,
      value: false,
    },
    // 从页面接收的所有可选品类列表
    allCategories: {
      type: Array as () => ICategory[],
      value: [],
    },
    // 当前条目在列表中的索引
    index: {
      type: Number,
      value: 0,
    },
  },
  data: {
    categoryPickerRange: [] as string[],
    pickerIndex: -1,
  },
  lifetimes: {
    attached() {
      // 组件加载时，根据所有品类列表生成 picker 需要的范围
      this.updatePickerRange();
    },
  },
  observers: {
    // 监听品类列表变化，自动更新 picker
    allCategories: function (newVal) {
      if (newVal && newVal.length > 0) {
        this.updatePickerRange();
      }
    },
    isCharityMode: function (isCharity) {
      // 当页面的计费模式改变时，重新计算当前条目的价格
      this.calculateAndEmit(this.data.item);
    },
  },
  methods: {
    updatePickerRange() {
      const categoryPickerRange = this.data.allCategories.map(
        (cat) => cat.categoryId[0].name
      );
      const pickerIndex = this.data.allCategories.findIndex(
        (cat) => cat.id === cat.categoryId[0]._id
      );
      this.setData({ categoryPickerRange, pickerIndex });
    },
    // 当用户选择了一个品类
    onCategoryChange(e: WechatMiniprogram.CustomEvent) {
      const selectedIndex = Number(e.detail.value);
      const selectedCategory = this.data.allCategories[selectedIndex];
      if (!selectedCategory) return;
      const updatedItem = {
        ...this.data.item,
        categoryId: selectedCategory.categoryId[0]._id,
        name: selectedCategory.categoryId[0].name,
        unit: selectedCategory.categoryId[0].defaultUnit,
        unitPrice: selectedCategory.unitPrice / 100,
      };
      this.setData({ pickerIndex: selectedIndex });
      this.calculateAndEmit(updatedItem);
    },
    handleTapDisabledInput() {
      wx.showToast({
        title: "请先选择回收品类",
        icon: "none",
        duration: 1500,
      });
    },
    // 当用户输入数量时
    onQuantityInput(e: WechatMiniprogram.CustomEvent) {
      const quantity = e.detail.value;
      const updatedItem = {
        ...this.data.item,
        quantity,
      };
      this.calculateAndEmit(updatedItem);
    },
    calculateAndEmit(item: IOutboundItem) {
      const quantity = parseFloat(item.quantity) || 0;
      let calculatedPrice = 0;

      // 如果全局是公益模式，或单价不存在，价格为0
      if (this.data.isCharityMode || !item.unitPrice) {
        calculatedPrice = 0;
      } else {
        // 否则正常计算
        calculatedPrice = quantity * item.unitPrice;
      }

      const finalItem = {
        ...item,
        totalPrice: calculatedPrice.toFixed(2),
      };

      this.triggerEvent("update", { index: this.data.index, item: finalItem });
    },

    // 删除此条目
    onDelete() {
      // 触发 'delete' 事件，将索引传给父页面
      this.triggerEvent("delete", { index: this.data.index });
    },
  },
});
